<template>
  <div v-loading="loading">
    <el-row style="margin-bottom: 5px;margin-right:10px;">
      <el-col :span="24">
        <div style="float: left;">
          <bread-crumb style="margin-left: 11px;" :child-data="subFunNo" class="card-bread-crumb"></bread-crumb>
        </div>
        <div style="float: right">
          <el-button
            v-if="funNo == '1501'"
            type="primary"
            icon="el-icon-refresh"
            size="mini"
            @click="refresh"
          >刷新</el-button>
          <el-button
            icon="el-icon-time"
            size="mini"
            @click="openBrowsingHistory"
            v-if="showButton.browsingHistory"
          >浏览记录</el-button>
          <el-button
            icon="el-icon-folder-delete"
            size="mini"
            @click="clearSign"
            v-if="showButton.cancelIssue"
          >撤销签发</el-button>
          <el-button
            icon="el-icon-paperclip"
            size="mini"
            @click="openAddFile"
            v-if="showButton.fileUpload"
            v-show="showFoot"
          >上传附件</el-button>
          <el-button
            icon="el-icon-reading"
            size="mini"
            @click="openAddReview"
            v-if="showButton.review"
          >检阅单据</el-button>
          <el-button
            icon="el-icon-upload2"
            size="mini"
            @click="openSubmit"
            v-if="showButton.submit"
            v-show="showFoot"
          >单据提交</el-button>
          <el-button
            icon="el-icon-edit"
            size="mini"
            @click="openAddSign"
            v-if="showButton.issue"
            v-show="showFoot"
          >单据签发</el-button>
          <el-button
            icon="el-icon-download"
            size="mini"
            @click="exportFile"
            v-if="showButton.export"
          >单据导出</el-button>
          <el-button
            icon="el-icon-refresh-left"
            size="mini"
            @click="revokeReceipt"
            v-if="showButton.revoke"
          >单据撤回</el-button>
          <el-button type="warning" plain icon="el-icon-help" size="mini" @click="handleHelp">帮助</el-button>
          <el-button
            icon="el-icon-close"
            size="mini"
            @click="back"
            v-if="queryParams.backChangeClose"
          >关闭</el-button>
          <el-button
            icon="el-icon-back"
            size="mini"
            @click="back"
            v-if="!queryParams.backChangeClose"
          >返回</el-button>
        </div>
      </el-col>
    </el-row>

    <el-tabs
      type="border-card"
      v-model="activeTab"
      @tab-click="handleTab"
      :before-leave="beforeLeave"
      style="margin-left:10px;margin-right:10px;margin-top:12px;"
    >
      <el-tab-pane v-for="(item,index) in childlist" :name="`tab-${index}`" v-bind:key="index">
        <span slot="label">
          <i :class="index==0 ? 'el-icon-reading' :'el-icon-s-operation'"></i>
          {{ item.ctFunName }}
        </span>
        <div
          class="div-height"
          :style="{'height' : tabMinHeight, 'min-height': tabMinHeight,'overflow':'auto'}"
        >
          <div class="vif" v-if="vif">
            <div

              class="default_vue"
              :ref="`default_vue${index}`"
              :id="`default_vue${index}`"
              :style="{'overflow':'auto','height':tabMinHeight}"
            >
              <div></div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane name="tabUrl" key="tabUrl" v-if="showButton.linkTab && handleType != 'add'">
        <span slot="label">
          <i class="el-icon-link"></i> 链接信息
        </span>
        <div class="div-height" :style="{'height' : tabMinHeight,'overflow':'auto'}">
          <url-list ref="tabUrlList"></url-list>
        </div>
      </el-tab-pane>
      <el-tab-pane
        name="tabFiles"
        key="tabFiles"
        v-if="showButton.fileUploadTab && handleType != 'add'"
      >
        <span slot="label">
          <i class="el-icon-paperclip"></i> 附件信息
          <el-badge ref="FileCount" :value="countFile" class="item" type="success"></el-badge>
        </span>
        <div class="div-height" :style="{'height' : tabMinHeight,'overflow':'auto'}">
          <list-files @updateTotal="getFileCount" ref="tabFilesList"></list-files>
        </div>
      </el-tab-pane>
      <el-tab-pane
        name="tabReviews"
        key="tabReviews"
        v-if="showButton.reviewTab && handleType != 'add'"
      >
        <span slot="label">
          <i class="el-icon-reading"></i> 检阅信息
          <el-badge ref="ReviewCount" :value="countReview" class="item" type="warning"></el-badge>
        </span>
        <div class="div-height" :style="{'height' : tabMinHeight,'overflow':'auto'}">
          <list-reviews @func="getReviewCount" ref="tabReviewsList"></list-reviews>
        </div>
      </el-tab-pane>
      <el-tab-pane name="tabSigns" key="tabSigns" v-if="isStep && handleType != 'add'">
        <span slot="label">
          <i class="el-icon-edit-outline"></i> 签发信息
          <el-badge ref="SignCount" :value="cuntSign" class="item" type="primary"></el-badge>
        </span>
        <div class="div-height" :style="{'height' : tabMinHeight,'overflow':'auto'}">
          <list-sign @updateTotal="getSignCount" ref="tabSignsList"></list-sign>
        </div>
      </el-tab-pane>
    </el-tabs>

    <browsing-history ref="browsingHistory"></browsing-history>
    <add-files v-bind="$attrs" ref="addFileDig" @refreshFileList="refreshFileList"></add-files>
    <add-review
      ref="addReviewDig"
      :dialogFormData="queryParams"
      @refreshReviewList="refreshReviewList"
    ></add-review>
    <add-sign
      v-bind="$attrs"
      ref="addSignDig"
      :dialogFormData="queryParams"
      :dialogType="signType.sign"
      @refreshAction="back"
    ></add-sign>
    <add-sign
      v-bind="$attrs"
      ref="addSubmitDig"
      :dialogFormData="queryParams"
      :dialogType="signType.submit"
      @refreshAction="back"
    ></add-sign>
  </div>
</template>

<script>
  import ListFiles from '@/components/SpsPublic/FileList/ListFiles'
  import ListReviews from '@/components/SpsPublic/ReviewList/ListReviews'
  import ListSign from '@/components/SpsPublic/SignList/ListSign'
  import Vue from 'vue'
  import AddFiles from '@/components/SpsPublic/FileList/AddFiles'
  import AddReview from '@/components/SpsPublic/ReviewList/AddReview'
  import AddSign from '@/components/SpsPublic/SignList/AddSign'
  import UrlList from '@/components/SpsPublic/FileList/UrlList'
  import BreadCrumb from '@/components/SpsPublic/BreadCrumb/BreadCrumb'
  import store from '@/store/index'
  import { getFunNo } from '@/utils/party'
  import { getFunction } from '@/api/mis/function'
  import {
    withdraw,
    revoke,
    publishCheck,
  } from '@/components/SpsPublic/SignList/SignList'
  import BrowsingHistory from './browsingHistory.vue'
  import { getShowButton, exportData } from '@/api/mis/misButton.js'
  import {NAME} from '@/utils/config'
  export default {
    name: 'SpsMaster',
    props: {
      // 查询参数
      queryParams: {
        type: Object,
        default: () => {
          return {}
        },
      },
    },
    components: {
      AddSign,
      AddReview,
      AddFiles,
      BreadCrumb,
      ListSign,
      ListReviews,
      ListFiles,
      UrlList,
      BrowsingHistory,
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 主业务单据id
        bussId: null,
        // 功能号
        funNo: getFunNo(this.$route),
        vif: true,
        // 设置激活标签
        activeTab: 'tab-0',
        // 设置高度
        defaultHeight: 205, // 195顶部 ， 30 是 padding ， 60 是底部
        tabMinHeight: '220px',
        // 设置总数 签字
        cuntSign: 0,
        // 设置总数 检阅
        countReview: 0,
        // 附件个数
        countFile: 0,
        // 增加附件状态
        showAddFile: true,
        // 存在子表的列表集合
        childlist: null,
        singleStore: null,
        subSingleStore: null,
        isStep: true,
        // 单据提交类型，sign：签字，submit：提交
        signType: {
          sign: 'sign',
          submit: 'submit',
        },
        // 查看类型，新增：add，查看：view，编辑：edit，签字：sign
        handleType: 'view',
        subFunNo: null,
        isEnd: false,
        showFoot: false,
        // 按钮显示判断
        showButton: {
          // 浏览记录
          browsingHistory: false,
          // 撤销签发
          cancelIssue: false,
          // 附件上传
          fileUpload: false,
          // 检阅单据
          review: true,
          // 检阅单据tab
          reviewTab: true,
          // 单据提交
          submit: false,
          // 单据签发
          issue: false,
          // 单据导出
          export: true,
          // 附件上传tab
          fileUploadTab: true,
          // 链接信息tab
          linkTab: true,
        },
        showButtonRequest: {
          handleType: 'view',
          ifEnd: false,
          ctIfReview: '0',
          recipient: '',
          ifStep: false,
          ctIfFile: false,
        },
        tabList: {},
        canSave: false,
        subFunctionData: null,
        funPromise: null,
        store: store,
      }
    },
    created(){
      if(this.$route.fullPath === '/gzw/taskreportList') {
        this.funNo =getFunNo(this.$router.resolve({ name: NAME }).route)
      }
    },
    mounted() {
      window.addEventListener('resize', () => {
        this.setConHeight()
      })
    },
    methods: {
      // 撤回单据
      revokeReceipt() {
        const that = this
        this.$confirm(
          '是否确认撤回单据？ 撤回单据后，单据流程将退回至创建人，流程也将重新发起。',
          '确认撤回单据',
          {
            distinguishCancelAndClose: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
          }
        ).then(() => {
          // 调用后端撤销方法
          const param = {
            recipientType: 'p',
            recipient: this.store.getters.name,
            functionNo: this.subFunNo,
            businessNo: this.bussId,
          }
          revoke(param).then((res) => {
            if (res.code === 200) {
              this.$emit('back', true)
              this.$message({
                type: 'success',
                message: res.msg,
              })
              that.back()
            }
          })
        })
      },
      // 动态导入组件
      registerComponent(componentName) {
        let temp = componentName
        return Promise.resolve()
          .then(() => require(`@/views/${temp}`))
          .then((component) => {
            return Vue.extend(component.default)
          })
      },
      //回调刷新附件列表
      refreshFileList() {
        this.singleStore.changeList = true
        this.$refs.tabFilesList.getList()
      },
      //回调刷新检阅列表
      refreshReviewList() {
        this.$refs.tabReviewsList.getList()
      },
      // 重置选中的tab
      resetTabSelected() {
        this.activeTab = 'tab-0'
      },
      // 刷新数据
      refresh() {
        this.loading = true
        // 设置变量
        const that = this
        this.resetTabSelected()
        that.vif = false
        this.singleStore = store.getters.singleStore['main' + this.funNo]
        this.singleStore.funNo = this.funNo
        this.subFunNo = this.queryParams.selectedCt.ct_fun_no
        this.singleStore.subFunNo = this.subFunNo
        this.subSingleStore = {
          funNo: this.funNo,
          subFunNo: this.subFunNo,
        }
        this.handleType = this.singleStore.handleType
        if (this.handleType == 'add') {
          store.dispatch('resetSubSingleStore', this.subSingleStore)
          this.queryParams.selectedCt.ct_end_name = '未签发'
          this.queryParams.selectedCt.ct_id = undefined
          // 标签上的数值置0
          this.cuntSign = 0
          this.countReview = 0
          this.countFile = 0
        }
        // 首次执行该方法，获取该条记录的fun信息
        if (
          this.subFunctionData == null &&
          this.funNo != '9003' &&
          this.funNo != '9100'
        ) {
          this.funPromise = new Promise((resolve, reject) => {
            getFunction(this.subFunNo).then((response) => {
              if (response.code == 200 && response.data) {
                this.subFunctionData = response.data
                resolve()
              } else {
                this.$message.error(response.msg)
              }
            })
          })
        } else {
          this.funPromise = new Promise((resolve, reject) => {
            if (this.subFunctionData == null) {
              that.subFunctionData = that.singleStore.ctFun
            }
            resolve()
          })
        }
        this.funPromise.then(() => {
          const ctFun = this.subFunctionData
          /**
           * 新增操作: 新增subSingleStore
           * */
          if (that.singleStore.handleType == 'add') {
            that.subSingleStore.subFunNo = that.funNo
            store.dispatch('createSubSingleStore', that.subSingleStore)
          }
          that.vif = true
          that.isEnd =
            that.queryParams.selectedCt.ct_end_name == '已签发' &&
            this.handleType == 'edit'
          // 设置ifEnd、ifStep
          const ifEndModel = {
            funNo: that.funNo,
            subFunNo: that.subFunNo,
            ifEnd: that.isEnd,
          }
          store.dispatch('setIfEnd', ifEndModel)
          const ifStepModel = {
            funNo: that.funNo,
            subFunNo: that.subFunNo,
            ifStep: ctFun.ctIfStep == '1',
          }
          store.dispatch('setIfStep', ifStepModel)
          that.subSingleStore =
            that.singleStore.subSingleStore['sub' + that.subFunNo]
          // 接收人非当前登录人，改为查看模式
          const nickName = store.getters.name
          if (
            that.queryParams.selectedCt.ct_incept_p &&
            that.queryParams.selectedCt.ct_incept_p != nickName &&
            nickName != 'admin'
          ) {
            that.singleStore.handleType = 'view'
            that.handleType = 'view'
          }
          if (
            that.queryParams.selectedCt &&
            that.queryParams.selectedCt.ct_id == undefined &&
            that.subSingleStore.ctId != undefined
          ) {
            that.queryParams.selectedCt.ct_id = that.subSingleStore.ctId
          }
          that.bussId = that.queryParams.selectedCt.ct_id
          // 刷新按钮显示的标识
          const myStore = that.subSingleStore
          this.getShowButton()
          this.loading = true
          getShowButton(this.showButtonRequest).then((response) => {
            if (response.code === 200 && response.data != null) {
              that.showButton = response.data
              that.showButton.fileUploadTab =
                ctFun.ctIfFile == '1' && that.singleStore.handleType != 'add'
              that.showButton.linkTab = ctFun.ctIfSubmit == '1'
              that.showButton.reviewTab = ctFun.ctIfReview == '1'
              that.showButton.browsingHistory = myStore.ifEnd
              that.isStep = myStore.ifStep
              that.showButton.export =
                that.$route.path.indexOf('queryDynamicBi') === -1
              //查看是否有子表
              let base = [
                {
                  ctFunName: '基本信息',
                  funNo: that.subFunNo,
                  ctUrl: that.subFunctionData.ctUrl,
                },
              ]
              let temp = that.subFunctionData.childList || []
              temp.forEach(function (e) {
                base.push(e)
              })
              that.canSave = that.showButton.canSave
              that.childlist = base
              that.$nextTick(function () {
                that.vif = true
                that.childlist.forEach(function (element, index) {
                  that.tabList['tab-' + index] = {
                    bussid: that.bussId,
                    subFunNo: that.subFunNo,
                    canSave: that.canSave,
                    ctUrl: element.ctUrl,
                    ctChildFunNo: element.ctChildFunNo,
                    ctIfShowretrieve: element.ctIfShowretrieve,
                    ctWinIcon: element.ctWinIcon,
                    default_vue: 'default_vue' + index,
                    activeTab: index == 0 ? true : false,
                  }
                  if (index == 0) {
                    that.createChildVue(
                      that.bussId,
                      that.subFunNo,
                      that.canSave,
                      element,
                      'default_vue' + index
                    )
                  }
                })
                // 子表注册
                that.registerChildComponent(that.canSave)
              })

              that.loading = false
            }
          })
        })
      },
      // 获取showButton请求类
      getShowButton() {
        const that = this
        const myStore = that.subSingleStore
        const ctFun = this.subFunctionData
        // 获取showButton的请求参数
        this.showButtonRequest = {
          handleType: that.singleStore.handleType,
          ifEnd: myStore.ifEnd,
          ctIfReview: ctFun.ctIfReview,
          recipient: that.queryParams.selectedCt.ct_incept_p,
          ifStep: myStore.ifStep,
          ctIfFile: ctFun.ctIfFile,
          createUser: that.queryParams.selectedCt.ct_create_user,
          funNo: that.subFunNo,
          ctBranch: that.queryParams.selectedCt.ct_branch,
        }
        if (
          that.queryParams.selectedCt &&
          that.queryParams.selectedCt.selectedCt &&
          'add' === that.queryParams.selectedCt.selectedCt.handleType
        ) {
          this.showButtonRequest.createUser = that.store.getters.name
          this.showButtonRequest.ctBranch = that.subSingleStore.oldForm.ctBranch
        }
    /*    if (!this.showButtonRequest.ctBranch) {
          this.showButtonRequest.ctBranch =
            that.store.getters.branchInfo.manageBranchCode
        }*/
        if (that.$route.name == 'PublicRecord/Q9999') {
          // that.queryParams.selectedCt = that.store.getters.name
          //this.showButtonRequest.recipient = that.store.getters.name
        }
      },
      // 子表注册
      registerChildComponent(canSave) {
        // 链接信息
        if (this.showButton.linkTab && this.$refs['tabUrlList']) {
          this.$refs['tabUrlList'].queryParams.ctIdP = this.bussId
          this.$refs['tabUrlList'].canSave = canSave
          this.$refs['tabUrlList'].subFunNo = this.subFunNo
          this.$refs['tabUrlList'].getList()
        }
        // 附件列表
        if (this.showButton.fileUploadTab && this.$refs['tabFilesList']) {
          this.$refs['tabFilesList'].queryParams.ctIdP = this.bussId
          this.$refs['tabFilesList'].canSave = canSave
          this.$refs['tabFilesList'].getList()
        }
        // 检阅列表
        if (this.showButton.reviewTab && this.$refs['tabReviewsList']) {
          this.$refs['tabReviewsList'].queryParams.ctBussId = this.bussId
          this.$refs['tabReviewsList'].getList()
        }
        // 签字列表
        if (this.isStep && this.$refs['tabSignsList']) {
          this.$refs['tabSignsList'].queryParams.ctBussId = this.bussId
          this.$refs['tabSignsList'].getList()
        }
      },
      close() {
        this.$emit('back')
      },
      // 返回操作
      back() {
        this.resetTabSelected()
        store.dispatch('changeSingleStore', this.singleStore)
        this.subSingleStore =
          this.singleStore.subSingleStore['sub' + this.subFunNo]
        // 如果单击ctEnd=1且流程已结束 或 查看模式 则不判断form是否修改
        if (
          (this.subSingleStore && this.subSingleStore.ifEnd) ||
          this.singleStore.handleType === 'view'
        ) {
          this.vif = false
          store.dispatch('closeShowMaster', this.funNo)
          this.$emit('back', this.singleStore.changeList)
          return
        }
        if (this.subSingleStore && this.subSingleStore.changeForm == true) {
          this.$confirm('检测到未保存的内容，确定继续离开？', '确认信息', {
            distinguishCancelAndClose: true,
            confirmButtonText: '离开',
            cancelButtonText: '去保存',
          })
            .then(() => {
              this.vif = false
              store.dispatch('delSingleStore', this.funNo)
              store.dispatch('closeShowMaster', this.funNo)
              this.$emit('back', this.singleStore.changeList)
            })
            .catch((action) => {
              this.$message({
                type: 'info',
                message:
                  action === 'cancel'
                    ? '放弃离开，请点击页面的保存按钮进行数据保存'
                    : '确定离开了，数据未保存',
              })
            })
        } else {
          this.vif = false
          store.dispatch('closeShowMaster', this.funNo)
          this.$emit('back', this.singleStore.changeList)
        }
        store.dispatch('resetSubSingleStore', this.subSingleStore)
      },
      // 无判断返回
      noJudgeBack() {
        this.subSingleStore =
          this.singleStore.subSingleStore['sub' + this.subFunNo]
        this.$emit('back', this.singleStore.changeList)
      },
      // 帮助按钮事件
      handleHelp() {
        this.$router.push('/spsPublicRouter/helpPreview?funNo=' + this.subFunNo)
      },
      getFileCount(countData) {
        this.countFile = countData
      },
      //获取检阅总数
      getReviewCount(countdata) {
        //调用子组件的总数
        this.countReview = countdata
      },
      //获取子组件签字总数
      getSignCount(countdata) {
        this.cuntSign = countdata
      },
      //动态计算显示区域高度
      setConHeight() {
        this.tabMinHeight = document.body.clientHeight - this.defaultHeight + 'px'
      },
      openAddFile() {
        // 切换到file的tab
        this.activeTab = 'tabFiles'
        this.$refs['addFileDig'].handleOpenDialog()
      },
      openAddReview() {
        this.activeTab = 'tabReviews'
        this.$refs['addReviewDig'].handleOpenDialog()
      },
      openAddSign() {
        console.log(this.queryParams)
        const param = {
          businessNo: this.queryParams.selectedCt.ct_id,
          functionNo: this.queryParams.selectedCt.ct_fun_no,
        }
        publishCheck(param).then((res) => {
          if (res.code === 500) {
            console.log(res.msg)
            return
          }
          this.activeTab = 'tabSigns'
          this.$refs['addSignDig'].handleOpenDialog()
        })
      },
      openSubmit() {
        this.activeTab = 'tabSigns'
        this.$refs['addSubmitDig'].handleOpenDialog()
      },
      openBrowsingHistory() {
        const recordData = {
          functionNo: this.subFunNo,
          businessNo: this.bussId,
        }
        this.$refs['browsingHistory'].handleOpenDialog(recordData)
      },
      exportFile() {
        const recordData = {
          funNo: this.subFunNo,
          bussNo: this.bussId,
        }
        this.$confirm('下载当前业务单据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
        })
          .then(() => {
            exportData(recordData).then((response) => {
              this.$message({
                type: 'success',
                message: '下载成功!',
              })
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '取消了操作',
            })
          })
      },
      clearSign() {
        this.$confirm(
          '该业务已经签发，是否撤销？ 注意，撤销后，单据若属于KPI考核体系，则所获积分会自动撤销',
          '请确认',
          {
            distinguishCancelAndClose: true,
            confirmButtonText: '确认',
            cancelButtonText: '取消',
          }
        )
          .then(() => {
            withdraw({ businessNo: this.bussId, functionNo: this.funNo }).then(
              (response) => {
                this.msgSuccess('业务已撤销，系统自动会去刷新')
                //设置刷新状态
                store.dispatch('setChangeListTrue', this.funNo)
                this.back()
              }
            )
          })
          .catch((action) => {})
      },
      handleTab(e, a) {
        let tab = this.tabList[e.name]
        if (tab == undefined) {
          return
        }
        if (tab.activeTab == false || tab.ctIfShowretrieve == '1') {
          let temps = this.singleStore.subSingleStore['sub' + this.subFunNo]
          tab.bussid = temps.ctId
          this.createChildVue(
            tab.bussid,
            tab.subFunNo,
            this.canSave,
            tab,
            tab.default_vue
          )
          this.tabList[e.name].activeTab = true
        }
      },
      chooseTab(tab) {
        this.activeTab = tab
        this.tabList[tab].activeTab = true
      },
      beforeLeave() {
        let temps = this.singleStore.subSingleStore['sub' + this.subFunNo]
        if (!temps.ctId) {
          this.msgSuccess('请保存基本信息')
          return false
        }
      },
      // 列表调用创建详情页
      createChildVue(bussId, subFunNo, canSave, element, localdiv) {
        let el = this.$refs[localdiv][0].children[0]
        this.registerComponent(element.ctUrl).then((Component) => {
          this.vif = true
          let temp = {
            subFunNo,
            bussId,
            canSave,
            componentName: element.ctUrl,
            childFunNo: element.ctChildFunNo,
            masterRefresh: this.refresh,
            masterBack: this.back,
            chooseTab: this.chooseTab,
            noJudgeBack: this.noJudgeBack,
          }
          new Component({
            name: localdiv,
            el: el,
            data: temp,
            router: this.$router,
            store: this.store,
          })
        })
        this.setConHeight()
      },
    },
    watch: {
      // 观察handleType的变化,改变showFoot
      handleType() {
        this.showFoot = this.handleType == 'edit' || this.handleType == 'sign'
      },
    },
  }
</script>

<style scoped>
  .div-height {
    min-height: 100px;
  }
  .default_vue{
    border-bottom: 6px solid rgba(0, 0, 0, 0.12);
  }
</style>
